<?php

namespace app\admin\model;

use think\Model;

class Warehouse extends BaseModel
{
    protected $attributes = [
        'status' => [
            '0' => '停用',
            '1' => '启用'
        ],
        'is_customs_clearance' => [
            '0' => '否',
            '1' => '是'
        ]
    ];

    /**
     * 关联获取国家名称
     * @return \think\model\relation\BelongsTo
     */
    public function getCountryName()
    {
        return $this->country()->bind(['country_value' => 'name']);
    }
    public function country()
    {
        return $this->belongsTo(RegionCountry::class, 'country', 'id');
    }

    public function transactionCurrency()
    {
        return $this->hasOne('TransactionCurrency', 'id', 'transaction_currency_id');
    }

    /**
     * 关联获取城市名称
     * @return \think\model\relation\BelongsTo
     */
    public function getCityName()
    {
        return $this->city()->bind(['city_value' => 'name']);
    }
    public function city()
    {
        return $this->belongsTo(RegionCity::class, 'city', 'id');
    }




    /**
     * @describe 获取下拉框格式数据
     * @author: Bobo
     * @date: 2024-08-23 10:06:27
     * @param [type] @required
     * @return Renderable
     */
    public function getSelectOption(array $where, $fields = 'id, name')
    {
        $data = $this
            ->field($fields)
            ->where($where)
            ->select()
            ->toArray();

        $selectOption = [];
        foreach ($data as $option) {
            $selectOption[intval($option['id'])] = $option['name'];
        }
        return $selectOption;
    }

    public function getStatusTextAttr($value, $data)
    {
        return isset($this->attributes['status'][$data['status']]) ? $this->attributes['status'][$data['status']] : '';
    }

    public function getIsCustomsClearanceTextAttr($value, $data){
        return isset($this->attributes['is_customs_clearance'][$data['is_customs_clearance']]) ? $this->attributes['is_customs_clearance'][$data['is_customs_clearance']] : '';
    }

    public function getFieldEnum($field)
    {
        if ('ALL' === strtoupper($field)) {
            return [
                'status' => $this->attributes['status'],
                'is_customs_clearance' => $this->attributes['is_customs_clearance']
            ];
        } else {
            return [$field => $this->$field];
        }
    }
    /**
     * 获取一级仓库ID（如果传入的是二级仓库）
     * @param int $warehouseId 仓库ID（可能是一级或二级）
     * @return int 返回一级仓库ID
     */
    public function getTopLevelWarehouseId($warehouseId)
    {
        // 假设一级仓库parent_id为0，二级仓库parent_id为一级仓库ID
        $warehouse = $this->where('id','in', $warehouseId)->field('id, fl_warehouse_id')->select();

        $topIds = [];
        foreach ($warehouse as $wh) {
            $topIds[] = ($wh['fl_warehouse_id'] != null)
                ? $wh['fl_warehouse_id']
                : $wh['id'];
        }
        // 返回去重结果
        return array_unique($topIds);
    }
}
